<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
  <th:block th:include="include :: header('新增商品')"/>
  <th:block th:include="include :: select2-css"/>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
  <form class="form-horizontal m" id="form-product-gen">

    <div class="form-group" th:each="customRecord:${customRecords}">
      <label class="col-sm-3 control-label"><span th:text="${customRecord.name}"></span>：</label>

      <div class="col-sm-8">
        <label class="check-box" th:each="customRecordValue:${customRecord.customRecordValues}">
          <input th:name="'customRecord'+${customRecord.customRecordId}" type="checkbox" th:value="${customRecordValue.customRecordValueId}"
                 th:text="${customRecordValue.name}" th:disabled="${customRecordValue.status == '1'}">
        </label>


        <!--                <label th:each="role:${roles}" class="check-box">-->
        <!--                    <input name="role" type="checkbox" th:value="${role.roleId}" th:text="${role.roleName}" th:disabled="${role.status == '1'}">-->
        <!--                </label>-->

        <!--                <label class="checkbox-inline">-->
        <!--                    <input type="checkbox" value="option2" id="inlineCheckbox2">白色</label>-->
        <!--                <label class="checkbox-inline">-->
        <!--                    <input type="checkbox" value="option3" id="inlineCheckbox3">黑色</label>-->
      </div>
    </div>

    <div class="form-group">
      <label class="col-sm-3 control-label"></label>
      <a class="btn btn-primary btn-xs" href="javascript:void(0)" onclick="genSku()"><i class="fa fa-bug"></i>生成SKU</a>
    </div>

    <div class="form-group">
      <div class="col-sm-12 select-table table-striped">
        <table id="bootstrap-table"></table>
      </div>
    </div>

    <div class="form-group">
      <label class="col-sm-3 control-label"></label>
      <a class="btn btn-primary btn-xs" href="javascript:void(0)" onclick="getData()"><i class="fa fa-bug"></i>获取数据</a>
    </div>

  </form>
</div>
<th:block th:include="include :: footer"/>
<th:block th:include="include :: select2-js"/>
<script th:inline="javascript">
  var prefix = ctx + "product/sku";
  var product = [[${product}]];
  var customRecords = [[${customRecords}]];

  $(function () {
    var options = {
      showSearch: false,
      showRefresh: false,
      showToggle: false,
      showColumns: false,
      pagination: false,
      uniqueId: "userId",
      height: 400,
      columns: []
    };

    var columns = [{
      checkbox: true
    }];
    $.each(customRecords, function (index, customRecord) {
      var column = {};
      column.field = 'customRecord' + customRecord.customRecordId;
      column.title = customRecord.name;
      columns.push(column);
    });

    columns.push({
      field: 'barcode',
      title: '条码',
      width: "30%",
      formatter: function (value, row, index) {
        var html = $.common.sprintf("<input class='form-control' name='barcode[%s]' type='text' value='%s'>", row.orderNum, value);
        return html;
      }
    });
    columns.push({
      field: 'skuName',
      title: 'SKU名称',
      width: "30%"
    });
    // columns.push({
    //   field: 'orderNum',
    //   title: '显示顺序',
    //   width: "5%"
    // });
    columns.push({
      field: 'retailPrice',
      title: '零售价',
      width: "10%",
      formatter: function (value, row, index) {
        var html = $.common.sprintf("<input class='form-control' name='retailPrice[%s]' type='text' value='%s'>", row.orderNum, value);
        return html;
      }
    });
    columns.push({
      field: 'currentPrice',
      title: '实售价',
      width: "10%",
      formatter: function (value, row, index) {
        var html = $.common.sprintf("<input class='form-control' name='currentPrice[%s]' type='text' value='%s'>", row.orderNum, value);
        return html;
      }
    });

    options.columns.push(columns);

    $.table.init(options);
  });

  function genSku() {

    var skuCustomRecordValuess = [];
    $.each(customRecords, function (index, customRecord) {


      var checkedValues = $.form.selectCheckeds("customRecord" + customRecord.customRecordId);
      if (checkedValues == '') {
        return true;
      }

      var checkeds = checkedValues.split(",");

      var field = "customRecord" + customRecord.customRecordId;
      var customRecordValueIds = checkeds;

      var skuCustomRecordValues = [];
      $.each(customRecordValueIds, function (index, customRecordValueId) {
        var skuCustomRecordValue = {};
        skuCustomRecordValue.customRecordValueId = customRecordValueId;
        skuCustomRecordValue.field=field;
        skuCustomRecordValue.customRecordId = customRecord.customRecordId;
        skuCustomRecordValue.customRecordName = customRecord.name;

        $.each(customRecord.customRecordValues, function (index, customRecordValue) {
          if (customRecordValueId == customRecordValue.customRecordValueId) {
            skuCustomRecordValue.customRecordValueName = customRecordValue.name;
            skuCustomRecordValues.push(skuCustomRecordValue);
            return false;
          }
        });
      });

      skuCustomRecordValuess.push(skuCustomRecordValues);

    });

    console.log(skuCustomRecordValuess);
    var records = getCombination(skuCustomRecordValuess);
    console.log(records);
    $.each(records, function (index, record) {
      var row = {};

      row.skuName = product.productName;
      $.each(record, function (index, column) {
        row[column.field]=column.customRecordValueName;
        row.customRecordId=column.customRecordId;
        row.customRecordValueId = column.customRecordValueId;
        row.skuName = row.skuName + '&' + column.customRecordValueName;
      });

      row.barcode = '';
      row.orderNum = index + 1 ;
      row.retailPrice = product.retailPrice;
      row.currentPrice = product.currentPrice;
      row.productId = product.productId;

      $("#" + table.options.id).bootstrapTable('insertRow', {
        index: 0, // 你想插入到哪，0表示第一行
        row: row
      })

    });

  }

  function getCombination(array) {
    var resultArry=[];

    $.each(array, function (index, arrItem) {
      if(resultArry.length===0){
        resultArry=arrItem
      } else {
        var emptyArray=[];

        $.each(resultArry, function (index, item) {

          $.each(arrItem, function (index, value) {
            if(item instanceof Array){
              emptyArray.push([item.concat(value)])
            }else{
              emptyArray.push([item, value]);
            }
          });
        });
        resultArry=emptyArray
      }
    });
    return resultArry;
  }

  function getData(){
    var data = $("#" + table.options.id).bootstrapTable('getData');
    $.each(data, function (index, sku) {
      var barcode = $('input[name="barcode['+ sku.orderNum+']"]').val();
      sku.barcode=barcode;
    });
    alert(JSON.stringify(data))
  }

  function submitHandler() {
    var data = $("#" + table.options.id).bootstrapTable('getData');
    
    if (data == null || data.length === 0) {
      $.modal.alertError('请生成SKU！');
      return
    }

    var checkBarcode = false;
    var checkRetailPrice = false;
    var checkCurrentPrice = false;
    $.each(data, function (index, sku) {
      // var barcode = $("input[name='barcode['+ sku.orderNum+']']").val();
      var barcode = $('input[name="barcode['+ sku.orderNum+']"]').val();
      var retailPrice = $('input[name="retailPrice['+ sku.orderNum+']"]').val();
      var currentPrice = $('input[name="currentPrice['+ sku.orderNum+']"]').val();

      if (barcode == null || barcode === '') {
        checkBarcode = true;
      }
      if (retailPrice == null || retailPrice === '') {
        checkRetailPrice = true;
      }
      if (currentPrice == null || currentPrice === '') {
        checkCurrentPrice = true;
      }
      sku.barcode=barcode;
      sku.retailPrice=retailPrice;
      sku.currentPrice=currentPrice;
    });
    
    if (checkBarcode) {
      $.modal.alertError('请输入条码！');
      return;
    }
    if (checkRetailPrice) {
      $.modal.alertError('请输入零售价！');
      return;
    }
    if (checkCurrentPrice) {
      $.modal.alertError('请输入实售价！');
      return;
    }

    $.ajax({
        url: prefix + "/batch-add",
        type: "post",
        data: JSON.stringify(data),
        processData: false,
        contentType: 'application/json',
        success: function (result) {
          $.operate.saveSuccess(result);
        }
      })
  }

</script>
</body>
</html>